import { Select } from '../../js/gd-ui/select/index.es.js'

if (gugeeGobal.isLogin) {
    initSearch()
}

function initSearch() {
    getCommonData()
    initInputBlurEvent()
}

function initInputBlurEvent() {
    const taggedInput = document.getElementById('taggedUsername')
    taggedInput.addEventListener('focus', e => {
        if(gugeeGobal.roleId < 3) {
            let config = {
                class: '',
                content: 'Only available for ADVANCED version users or higher,upgrade now!',
                confirmBtnText: 'Upgrade',
                confirmBtn: {
                    event: () => {
                        showLoading()
                        window.location.href = '/pricing?refer=' + window.location.href
                    }
                },
                cancelBtnText: 'Not Now',
            }
            showModal(config)
        }
    })
    taggedInput.addEventListener('blur', e => {
        const name = e.target.getAttribute('name')
        params[name] = e.target.value
        params.page = 1
        if (!gugeeGobal.isMobile) {
            const selectedFilterItem = document.getElementById('selectedFilterItem')
            const text = e.target.value
            const label = e.target.previousElementSibling.innerText
            const selectedWrap = document.getElementById('selectedWrap')
            const selectedItem = selectedWrap && selectedWrap.querySelector('[data-label="' + label + '"]')
            if (selectedItem) {
                if(text) {
                    selectedItem.querySelector('.selected-item__inner').innerHTML = '<span>' + label + ': </span>' + text
                } else {
                    selectedItem.remove()
                    if(!selectedWrap.innerHTML) {
                        selectedFilterItem.hide()
                    }
                }
            } else {
                if(text) {
                    const item = document.createElement('div')
                    item.className = 'selected-item'
                    item.setAttribute('data-label', label)
                    const inner = document.createElement('div')
                    inner.className = 'selected-item__inner'
                    inner.innerHTML = '<span>' + label + ': </span>' + text
                    item.appendChild(inner)
                    const icon = document.createElement('i')
                    icon.className = 'iconfont iconbuzhichi'
                    icon.addEventListener('click', () => {
                        item.remove()
                        params[name] = undefined
                        params.page = 1
                        e.target.value = ''
                        searchUser()
                    })
                    item.appendChild(icon)
                    selectedWrap.appendChild(item)
                    selectedFilterItem.show('flex')
                }
            }
            searchUser()
        }
    })
    if(!gugeeGobal.isMobile) {
        taggedInput.addEventListener('keydown', e => {
            if(e.key === 'Enter') {
                taggedInput.blur()
            }
        })
    }
}

function getCommonData() {
    Promise.all([getCategory(), getRegion(), getLanguage()]).then(res => {
        const allOption = '<li class="gd-option is-active">All</li>'
        let str = ''
        if (res[0].Code === 200) {
            str = allOption
            const categoryPrimary = document.getElementById('categoryPrimary')
            res[0].Data.forEach(item => {
                str += '<li class="gd-option" value="' + item.overallCategory + '">' + item.overallCategory + '</li>'
            })
            categoryPrimary.innerHTML = str
        }
        if (res[1].Code === 200) {
            str = allOption
            const region = document.getElementById('influencerRegion')
            const audienceRegion = document.getElementById('audienceRegion')
            res[1].Data.forEach(item => {
                str += '<li class="gd-option" value="' + item.code + '">' + item.name + '</li>'
            })
            region.innerHTML = str
            audienceRegion.innerHTML = str
        }
        if (res[2].Code === 200) {
            str = allOption
            const language = document.getElementById('influencerLanguge')
            const audienceLanguage = document.getElementById('audienceLanguage')
            res[2].Data.forEach(item => {
                str += '<li class="gd-option" value="' + item.code + '">' + item.name + '</li>'
            })
            language.innerHTML = str
            audienceLanguage.innerHTML = str
        }
        let select = new Select()
        if(gugeeGobal.roleId < 3) {
            select.setBeforeSelectEvent(noPermissionEvent)
        } else {
            select.setSelectedEvent(selectedEvent)
        }
        select.init()
    }).catch(err => {
        console.error(err)
    })
}

function getCategory() {
    return _axios.get('/ins/dic/overall/category')
}

function getRegion() {
    const url = getEncodeUrl('/ins/dic/region',{
        type: 1
    })
    return _axios.get(url)
}

function getLanguage() {
    const url = getEncodeUrl('/ins/dic/language', {
        type: 1
    })
    return _axios.get(url)
}

function getSecondCategory(catagory) {
    const wrap = document.getElementById('secondaryPrimary')
    clearSecondarySelected()
    if (!catagory) {
        wrap.innerHTML = ''
        params.primaryCategory = undefined
        return false
    }
    let url = getEncodeUrl('/ins/dic/category', {
        overallCategory: catagory
    })
    _axios.get(url).then(res => {
        if (res.Code === 200) {
            let str = '<li class="gd-option" value="">All</li>'
            res.Data.forEach(item => {
                str += '<li class="gd-option" value="' + item.category + '">' + item.category + '</li>'
            })
            wrap.innerHTML = str
            let selectWrap = wrap.parentElement.parentElement
            let select = new Select()
            select.setElement([selectWrap])
            select.setSelectedEvent(selectedEvent)
            select.init()
        }
    })
}

function clearSecondarySelected() {
    const wrap = document.getElementById('secondaryPrimary')
    let selectWrap = wrap.parentElement.parentElement
    selectWrap.querySelector('.label').innerText = 'Secondary'
    const secondarySelectedItem = document.querySelector('#selectedWrap [data-label="Secondary"]')
    if (secondarySelectedItem) {
        secondarySelectedItem.remove()
    }
    params.secondCategory = undefined
}

function noPermissionEvent(e) {
    let config = {
        content: 'Only available for ADVANCED version users or higher,upgrade now!',
        confirmBtnText: 'Upgrade',
        confirmBtn: {
            event: () => {
                window.location.href = '/pricing?refer=' + window.location.href
            }
        },
        cancelBtnText: 'Not Now',
    }
    showModal(config)
}
// 选中项事件
function selectedEvent(e) {
    const ul = e.target.parentElement
    const name = ul.getAttribute('name')
    const value = e.target.getAttribute('value')
    const label = ul.getAttribute('label')
    params[name] = value
    if (ul.id === 'categoryPrimary') {
        getSecondCategory(value)
    }
    // pc端
    if (!gugeeGobal.isMobile) {
        params.page = 1
        const selectedFilterItem = document.getElementById('selectedFilterItem')
        const selectedWrap = document.getElementById('selectedWrap')
        const selectedItem = selectedWrap.querySelector('[data-label="' + label + '"]')
        if (selectedItem) {
            if(e.target.innerText === 'All') {
                selectedItem.remove()
                if(!selectedWrap.innerHTML){
                    selectedFilterItem.hide()
                }
                params[name] = undefined
                ul.parentElement.parentElement.querySelector('.label').innerText = label
                searchUser()
                return false
            } else {
                selectedItem.querySelector('.selected-item__inner').innerHTML = '<span>' + label + ': </span>' + e.target.innerText
            }
        } else {
            const item = document.createElement('div')
            item.className = 'selected-item'
            item.setAttribute('data-label', label)
            const inner = document.createElement('div')
            inner.className = 'selected-item__inner'
            inner.innerHTML = '<span>' + label + ': </span>' + e.target.innerText
            item.appendChild(inner)
            const icon = document.createElement('i')
            icon.className = 'iconfont iconbuzhichi'
            icon.addEventListener('click', () => {
                if (item.getAttribute('data-label') === 'Primary') {
                    clearSecondarySelected()
                }
                item.remove()
                params[name] = undefined
                params.page = 1
                if(!selectedWrap.innerHTML){
                    selectedFilterItem.hide()
                }
                ul.parentElement.parentElement.querySelector('.label').innerText = label
                ul.querySelector('.is-active').classList.remove('is-active')
                ul.querySelectorAll('li')[0].classList.add('is-active')
                searchUser()
            })
            item.appendChild(icon)
            selectedWrap.appendChild(item)
        }
        selectedFilterItem.show('flex')
        searchUser()
    }
}
